package org.itboys.weixin.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinMenu;
import org.itboys.weixin.tools.WeixinMenuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

/**
 * 微信自定义菜单管理
 * @author chenzhiqi
 *
 */
@Service
public class WeixinMenuService extends BaseWeixinService<WeixinMenu, Long> {

	private static final long serialVersionUID = -4312050710300845641L;
	
	@Autowired
	private WeixinConfigService weixinConfigService;
	
	@Resource(name="weixinDS")
	private MongoDataSource weixinMenuDataSource;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return weixinMenuDataSource;
	}

	@Override
	protected Class<WeixinMenu> getEntityClass() {
		return WeixinMenu.class;
	}
	
	public void save(WeixinMenu detail){
		detail.setCreateTime(new Date());
		detail.setCreator(AdminSessionHolder.getAdminUserId());
		super.save(detail);
	}
	
	public void update(WeixinMenu detail){
		WeixinMenu detail2 = getById(detail.getId());
		detail.setCreateTime(detail2.getCreateTime());
		detail.setCreator(detail2.getCreator());
		detail.setUpdater(AdminSessionHolder.getAdminUserId());
		detail.setUpdateTime(new Date());
		super.update(detail);
	}
	
	/**
	 * 根据微信配置表的ID 同步自定义菜单
	 * @author cehnzhiqi
	 * @param weixinId weixin_config表的主键
	 * @return
	 */
	public int doSyncWeixinMenu(long weixinId){
		WeixinConfig wx=weixinConfigService.getById(weixinId);
		String appId = wx.getAppId();
		String appScret = wx.getAppSecret();
		//ResourceLoader resourceLoader = new DefaultResourceLoader();
		//Resource resource = resourceLoader.getResource("testMenu.json");
		//String jsonMenu = IOUtils.inputStream2String(resource.getInputStream());
		String jsonMenu = WeixinMenuUtils.menu2Json(list1(weixinId));
		System.out.println(jsonMenu);
		//创建微信菜单
		int createResult = WeixinMenuUtils.doCreateWeixinMenu(appId, appScret, jsonMenu);
		return createResult;
	}
	
	public boolean checkvalue(Long id,Long weixinId,String value){
		boolean flag=false;
		List<WeixinMenu> list=list1(weixinId);
		for(WeixinMenu wm : list){
			if(wm.getValue().equals(value)&&wm.getId()!=id){
				flag=true;
			}
		}
		return flag;
	}
	
	public List<WeixinMenu> list1(Long weixinID){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
		param.put("weixinId", weixinID);
		return super.list(param);
	}
	
}